// API service for communicating with the backend
const API_BASE_URL = '/api';

class ApiService {
  constructor() {
    this.baseUrl = API_BASE_URL;
  }

  // Generic fetch method with error handling
  async fetch(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    
    try {
      const response = await fetch(url, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
        ...options,
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error(`Error fetching ${url}:`, error);
      throw error;
    }
  }

  // Project APIs
  async createProject(projectData) {
    return this.fetch('/projects', {
      method: 'POST',
      body: JSON.stringify(projectData),
    });
  }

  async getProject(projectId) {
    return this.fetch(`/projects/${projectId}`);
  }

  async updateProject(projectId, projectData) {
    return this.fetch(`/projects/${projectId}`, {
      method: 'PUT',
      body: JSON.stringify(projectData),
    });
  }

  async getProjects() {
    return this.fetch('/projects');
  }

  // Timeline APIs
  async getTimeline(projectId) {
    return this.fetch(`/timelines/${projectId}`);
  }

  async updateTimeline(timelineId, timelineData) {
    return this.fetch(`/timelines/${timelineId}`, {
      method: 'PUT',
      body: JSON.stringify(timelineData),
    });
  }

  // Asset APIs
  async getAssets(projectId) {
    return this.fetch(`/assets/${projectId}/assets`);
  }

  async getAsset(projectId, assetId) {
    return this.fetch(`/assets/${projectId}/assets/${assetId}`);
  }

  async uploadAsset(projectId, assetData) {
    return this.fetch(`/assets/${projectId}/assets`, {
      method: 'POST',
      body: JSON.stringify(assetData),
    });
  }

  async deleteAsset(projectId, assetId) {
    return this.fetch(`/assets/${projectId}/assets/${assetId}`, {
      method: 'DELETE',
    });
  }

  // Render APIs
  async startPreview(projectId) {
    return this.fetch('/render/preview', {
      method: 'POST',
      body: JSON.stringify({ projectId }),
    });
  }

  async exportVideo(exportParams) {
    return this.fetch('/render/export', {
      method: 'POST',
      body: JSON.stringify(exportParams),
    });
  }

  async getRenderStatus(taskId) {
    return this.fetch(`/render/jobs/${taskId}`);
  }
}

export default new ApiService();